$(function () {

    $("#registrationTime").datetimepicker({//选择年月日
        format: 'yyyy-mm-dd',
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,//显示‘今日’按钮
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,  //Number, String. 默认值：0, 'hour'，日期时间选择器所能够提供的最精确的时间选择视图。
        clearBtn:true,//清除按钮
        forceParse: 0
    });

    $("#jqGrid").jqGrid({
        url: baseURL + 'manage/operation/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true },
			{ label: '公司名称', name: 'corporateName', index: 'corporate_name', width: 80 }, 			
			{ label: '注册地址', name: 'registeredAddres', index: 'registered_addres', width: 80 }, 			
			{ label: '注册时间', name: 'registrationTime', index: 'registration_time', width: 80 }, 			
			{ label: '公司代码', name: 'companyCode', index: 'company_code', width: 80 }, 			
			{ label: '法人', name: 'legalPerson', index: 'legal_person', width: 80 }, 			
			{ label: '公司性质', name: 'companyNature', index: 'company_nature', width: 80 }, 			
			{ label: '现任董事长', name: 'currentChairman', index: 'current_chairman', width: 80 }, 			
			{ label: '公司所在地址', name: 'locationCompany', index: 'location_company', width: 80 }, 			
			{ label: '现公司地址', name: 'companyAddress', index: 'company_address', width: 80 }, 			
			{ label: '员工数量', name: 'numberEmployees', index: 'number_employees', width: 80 }, 			
			{ label: '经营范围', name: 'businessScope', index: 'business_scope', width: 80 },
            { label: '备注', name: 'state', index: 'state', width: 50 ,formatter: function(value, options, row){
                    return value === 2 ?
                        '<span class="label label-danger">禁用</span>' :
                        '<span class="label label-success">正常</span>';
            }},
            { label: '备注', name: 'remarks', index: 'remarks', width: 80 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        },
        onSelectRow:function (id) {
            console.log("onSelectRow");
            if(id === null){
                layer.alert("请选择一条记录");
            }
            $("#userGrid").jqGrid("clearGridData");
            $("#userGrid").jqGrid('setGridParam',{
                url:"/sys/user/listByOpId?opId="+id
            }).trigger("reloadGrid");
        }
    });

    $("#userGrid").jqGrid({
        datatype: "json",
        colModel: [
            { label: '用户ID', name: 'userId', index: "user_id", width: 45, key: true },
            { label: '用户名', name: 'username', width: 75 },
            { label: '邮箱', name: 'email', width: 90 },
            { label: '手机号', name: 'mobile', width: 100 },
            { label: '状态', name: 'status', width: 60, formatter: function(value, options, row){
                        return value === 0 ?
                            '<span class="label label-danger">禁用</span>' :
                            '<span class="label label-success">正常</span>';
                }},
            { label: '创建时间', name: 'createTime', index: "create_time", width: 85},
            { label: '操作', name: 'state', index: 'state', width: 50, edittype:"button", formatter: function(cellValue,grid, rows, state) {
                    if(rows.status == 1){
                        return "<button class='btn btn-primary ' onclick=\"vm.stopUser(" + rows.userId+")\">正常</button>" ; }else{
                        return "<button class='btn btn-warning ' >已禁用</button>" ; }
                }}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: false,
        pager: "#userGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#userGridPager").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        showUserList:true,
        showAddUser: true,
        showAddOperation:false,
        selectId:null,
		title: null,
		operation: {},
        user:{}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
            vm.showUserList = false;
            vm.showAddUser = false;
            vm.showAddOperation = true;
			vm.title = "新增";
			vm.operation = {};
		},
		update: function (event) {
			var id = getSelectedRowId();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.showUserList = false;
            vm.showAddUser = false;
            vm.showAddOperation = true;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
        addUser:function(event){
            vm.selectId = getSelectedRowId();
            if(vm.selectId === null){
                alert("请选择一条记录");
                return ;
            }
		    vm.user = {};
            vm.showAddUser = true;
            vm.showList = false;
            vm.showUserList = false;
            vm.showAddOperation = false;

        },
        saveUser:function(event){
            vm.user.deptId = vm.selectId;
            $.ajax({
                type: "POST",
                url: baseURL + "sys/user/saveManageUser",
                contentType: "application/json",
                data: JSON.stringify(vm.user),
                success: function(r){
                    if(r.code === 0){
                        layer.msg("操作成功", {icon: 1});
                        vm.reload();
                    }else{
                        layer.alert(r.msg);
                        return;
                    }
                }
            });
        },
		saveOrUpdate: function (event) {
            vm.operation.registrationTime = $("#registrationTime").data("datetimepicker").getDate();
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.operation.id == null ? "manage/operation/save" : "manage/operation/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.operation),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
        stopUser:function(event){
            if(event === null){
                alert("请选择一条记录");
                return ;
            }
            var lock = false;
            layer.confirm('确定要停用选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(!lock) {
                    lock = true;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "sys/user/stopUser",
                        dataType: "json",
                        data: {userId:event},
                        success: function(r){
                            if(r.code === 0){
                                layer.msg("操作成功", {icon: 1});
                                vm.reload();
                            }else{
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            }, function(){
            });
        },
        stopUsing:function(event){
            var ids = getSelectedRowId();
            if(ids == null){
                alert("请选择一条记录");
                return ;
            }
            var lock = false;
            layer.confirm('确定要停用选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(!lock) {
                    lock = true;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "manage/operation/stopUsing",
                        dataType: "json",
                        data: {opId:ids},
                        success: function(r){
                            if(r.code === 0){
                                layer.msg("操作成功", {icon: 1});
                                vm.reload();
                            }else{
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            }, function(){
            });
        },
		del: function (event) {
			var ids = getSelectedRowId();
			if(ids == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "manage/operation/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(id){
			$.get(baseURL + "manage/operation/info/"+id, function(r){
                vm.operation = r.operation;
            });
		},
		reload: function (event) {
			vm.showList = true;
			vm.showUserList = true;
			vm.showAddUser = false;
            vm.showAddOperation = false;
            vm.selectId = null;
            $("#userGrid").jqGrid("clearGridData");
            var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		}
	}
});